//
//  Main1ViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/8/26.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "Main1ViewController.h"
#import "Prefix.h"
#import "UIColor+Hex.h"
#import "UserDefaultUtil.h"
#import "MBProgressHUD+MJ.h"
#import "UserDefaultUtil.h"
#import "HttpReauestParam.h"
#import "AFHTTPRequestOperationManager.h"
#import "NoticeViewController.h"
#import "NoticeDetailViewController.h"
#import "OrderDetailViewController.h"
#import "SearchOrderViewController.h"
#import "MainUITabBarController.h"
#define ScreenHeight [[UIScreen mainScreen] bounds].size.height//获取屏幕高度，兼容性测试
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width//获取屏幕宽度，兼容性测试
@interface Main1ViewController ()

@property NSArray *imageData;
@property NSArray *msgData;
@property NSArray *orderData;

@property NSInteger msg_height;
@end

@implementation Main1ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];

    
//    for(UIView * view in self.view.subviews){
//        
//        view.frame = AUTOFITSCREEN_FOR_COORDINATE(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
//    }
    
    [self.scrollView addSubview:self.sdScrollView];
    self.scrollView.contentSize = self.view.bounds.size;
    self.scrollView.alwaysBounceHorizontal = NO;
    self.scrollView.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    
    self.topView.layer.cornerRadius = 4;
    self.topView.backgroundColor = [UIColor colorWithHexString:@"#d9d9d9"];
    
    [self.view viewWithTag:11].backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    [self.view viewWithTag:22].backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    [self.view viewWithTag:33].backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    
    NSArray *imagesURLStrings = @[
                                  @"https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a4b3d7085dee3d6d2293d48b252b5910/0e2442a7d933c89524cd5cd4d51373f0830200ea.jpg",
                                  @"https://ss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a41eb338dd33c895a62bcb3bb72e47c2/5fdf8db1cb134954a2192ccb524e9258d1094a1e.jpg",
                                  @"http://c.hiphotos.baidu.com/image/w%3D400/sign=c2318ff84334970a4773112fa5c8d1c0/b7fd5266d0160924c1fae5ccd60735fae7cd340d.jpg"
                                  ];

    
    self.sdScrollView.imageURLStringsGroup = imagesURLStrings;
    self.sdScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    self.sdScrollView.delegate = self;
    self.sdScrollView.currentPageDotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    self.sdScrollView.placeholderImage = [UIImage imageNamed:@"placeholder"];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [self getCountData];
    [super viewWillAppear:animated];
}
/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
    UIStoryboard *sb= [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    
    NoticeDetailViewController *vc = [sb instantiateViewControllerWithIdentifier:@"notice_detail_view"];
    vc.noticeId = _imageData[index][@"id"];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)viewDidAppear:(BOOL)animated{
    
    [self getImageData];
    [self getMsgData];
    [super viewDidAppear:animated];
}
-(void)getImageData{
    
    NSString *userId = [UserDefaultUtil getUserId];
    NSDictionary *dic =@{@"identifier":userId};
    
    HttpReauestParam *param = [[HttpReauestParam alloc]initWithData:@"app_query_home_image" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        if ([data[@"success"] boolValue]) {
            
            NSArray *array = data[@"result"];
            
            NSMutableArray *picUrl = [[NSMutableArray alloc]init];
            for (int i = 0; i < array.count; i++) {
                [picUrl addObject:array[i][@"imgUrl"]];
            }
            _imageData = array;
            self.sdScrollView.imageURLStringsGroup = picUrl;
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];

}
-(void)getCountData{
    
    NSString *userId = [UserDefaultUtil getUserId];
    NSDictionary *dic =@{@"identifier":userId};
    
    HttpReauestParam *param = [[HttpReauestParam alloc]initWithData:@"home_order_number" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        if ([data[@"success"] boolValue]) {
            NSString *result = data[@"result"];
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            
            if ([dic[@"appointmentNum"] integerValue] > 0) {
                _lab_oppoint.text = [NSString stringWithFormat:@"待预约(%@)",dic[@"appointmentNum"]];
            }else{
                _lab_oppoint.text = @"待预约";
            }
            if ([dic[@"pickupNum"] integerValue] > 0) {
                _lab_pickup.text = [NSString stringWithFormat:@"待提货(%@)",dic[@"pickupNum"]];
            }else{
                _lab_pickup.text = @"待提货";
            }

            if ([dic[@"signNum"] integerValue] > 0) {
                _lab_sign.text = [NSString stringWithFormat:@"待签收(%@)",dic[@"signNum"]];
            }else{
                _lab_sign.text = @"待签收";
            }
            if ([dic[@"problemNum"] integerValue] > 0) {
                _lab_problem.text = [NSString stringWithFormat:@"问题件(%@)",dic[@"problemNum"]];
            }else{
                _lab_problem.text = @"问题件";
            }
            
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
    
}
-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
- (IBAction)notice_click:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    NoticeViewController *vc = [sb instantiateViewControllerWithIdentifier:@"notice_view"];
    [self.navigationController pushViewController:vc animated:YES];
}

-(int)setMsgView:(NSArray *) array{
    UIView *msgTitle = [self.view viewWithTag:10001];
    UIView *contentView = [self.view viewWithTag:1001];
    if (contentView != nil) {
        [contentView removeFromSuperview];
    }
    contentView = [[UIView alloc]init];
    contentView.tag = 1001;
    
    int count = 3;
    if (array.count < 3) {
        count = array.count;
    }
    
    int height = 1;
    for (int i = 0; i < count; i++) {
        
        UIControl *control = [[UIControl alloc]initWithFrame:CGRectMake(0, height , ScreenWidth, 35)];
        [control addTarget:self action:@selector(msg_click:) forControlEvents:UIControlEventTouchUpInside];
        control.tag = i;
        control.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, height, 35, 35)];
        imageView.contentMode = UIViewContentModeCenter;
        if ([array[i][@"isRead"] longValue] == 0) {
            imageView.image = [UIImage imageNamed:@"main1_msg_image"];
        }
        
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(45, height, ScreenWidth - 55, 35)];
        lab.text = array[i][@"content"];
        lab.font = [UIFont systemFontOfSize:13];
        [contentView addSubview:control];
        [contentView addSubview:imageView];
        [contentView addSubview:lab];
        
        height  = height + 35;
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, height, ScreenWidth, 1)];
        line.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
        
        [contentView addSubview:line];
        height  = height + 1;
    }
    contentView.frame = CGRectMake(0, msgTitle.frame.origin.y + msgTitle.frame.size.height,ScreenWidth , height);
    [self.scrollView addSubview:contentView];
    
    _msg_height = height;
    
    [self getData];
    return height + msgTitle.frame.origin.y;
}

-(void) getMsgData{
    NSDate * date = [NSDate date];
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSCalendarUnitMonth | NSCalendarUnitDay;
    
    comps = [calendar components:unitFlags fromDate:date];
    
    int year = [comps year];
    
    int month = [comps month];
    
    NSString *userId =[UserDefaultUtil getUserId];
    NSString *startDate;
    NSString *endDate;
    
    startDate = [NSString stringWithFormat:@"%i-%i-01 00:00:00",year,month];
    if (month + 1 > 12) {
        endDate = [NSString stringWithFormat:@"%i-%i-01 00:00:00",year + 1,1];
    }else{
        endDate = [NSString stringWithFormat:@"%i-%i-01 00:00:00",year,month + 1];
    }
    
    NSDictionary * dic = @{@"identifier": userId ,@"page":[NSString stringWithFormat:@"%@",@"1"],@"size":[NSString stringWithFormat:@"%i",5],@"startDate":startDate,@"endDate":endDate};
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"app_AppMessage_List_Get" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    // [MBProgressHUD showMessage:@"获取订单"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        
        if ([data[@"success"] boolValue]) {
            
            NSArray *msgData = data[@"result"];
            _msgData = msgData;
            [self setMsgView:msgData];
        }else{
            //[MBProgressHUD showError:data[@"errorMsg"]];
            NSArray *msgData = [[NSArray alloc]init];
            _msgData = msgData;
            [self setMsgView:msgData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

-(void)setOrderView:(NSArray *)orderData{
    
    UIView *contentView = [self.view viewWithTag:1001];
    
    _msg_height = _msg_height + 10;
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, _msg_height, ScreenWidth, 45)];
    title.text = @"    今日订单";
    title.font = [UIFont systemFontOfSize:14];
    title.backgroundColor = [UIColor whiteColor];
    [contentView addSubview:title];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0,_msg_height , ScreenWidth, 1)];
    line.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    [contentView addSubview:line];
    _msg_height = _msg_height + 46;
    
    for (int i = 0; i < orderData.count; i++) {
        NSDictionary *dic = orderData[i];
        
        UIControl *control2 = [[UIControl alloc]initWithFrame:CGRectMake(0, _msg_height, ScreenWidth, 148)];
        control2.tag = i + 100;
        [control2 addTarget:self action:@selector(order_click2:) forControlEvents:UIControlEventTouchUpInside];
        //[control2 sendActionsForControlEvents:UIControlEventTouchUpInside];
        
      
        control2.backgroundColor = [UIColor whiteColor];

        [contentView addSubview:control2];
        
        //来源图片
        UIImageView *image1 = [[UIImageView alloc]initWithFrame:CGRectMake(10, _msg_height, 18, 32)];
        image1.contentMode = UIViewContentModeCenter;
        if ([dic[@"orderFrom"] isEqualToString:@"天猫"] || [dic[@"orderFrom"] isEqualToString:@"4PL-天猫"]) {
            image1.image = [UIImage imageNamed:@"grab_order_tm"];
        }
        if ([dic[@"orderFrom"] isEqualToString:@"极有家"]) {
            image1.image = [UIImage imageNamed:@"grab_order_jyj"];
        }
        if ([dic[@"orderFrom"] isEqualToString:@"其它"]) {
            image1.image = [UIImage imageNamed:@"grab_order_qt"];
        }
        if ([dic[@"orderFrom"] isEqualToString:@"京东"]) {
            image1.image = [UIImage imageNamed:@"order_order_from_jd"];
        }
        
        
        [contentView addSubview:image1];
        //单号
        NSString *serviceNo = [NSString stringWithFormat:@"%@(%@)",dic[@"serviceNo"],dic[@"serviceStatus"]];
        CGSize size = [serviceNo sizeWithFont:[UIFont systemFontOfSize:13]];
        UILabel *lab_orderNo = [[UILabel alloc]initWithFrame:CGRectMake(30, _msg_height, size.width, 32)];
        lab_orderNo.font = [UIFont systemFontOfSize:13];
        lab_orderNo.text = serviceNo;
        [contentView addSubview:lab_orderNo];
        //日期
        NSDateFormatter *sf = [[NSDateFormatter alloc]init];
        [sf setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        
        NSDateFormatter *sf2 = [[NSDateFormatter alloc]init];
        [sf2 setDateFormat:@"yyyy-MM-dd"];
        NSDate * date1 = [sf dateFromString:dic[@"serviceDate"]];
        
       
        
        NSString *date = [sf2 stringFromDate:date1];
        size = [date sizeWithFont:[UIFont systemFontOfSize:13]];
        UILabel *lab_orderDate = [[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth - 10 - size.width - 3 , _msg_height + 5 , size.width + 3, 22)];
        lab_orderDate.font = [UIFont systemFontOfSize:10];
        lab_orderDate.text = date;
        lab_orderDate.textAlignment = NSTextAlignmentCenter;
        NSString *appointmentTime = [NSString stringWithFormat:@"%@",dic[@"appointmentTime"]];
        if(appointmentTime != nil && ![appointmentTime isEqualToString:@""]){
            NSDate * date2 = [sf dateFromString:appointmentTime];
            if(date2.timeIntervalSince1970 - [NSDate date].timeIntervalSince1970 < 2* 60 * 60){
                [lab_orderDate.layer setBorderWidth:1];
                [lab_orderDate.layer setBorderColor:[UIColor colorWithHexString:@"ff7e00"].CGColor];
                lab_orderDate.textColor = [UIColor colorWithHexString:@"ff7e00"];
                lab_orderDate.layer.cornerRadius = 11 ;
                
                lab_orderDate.layer.masksToBounds = YES;
            }
        }
        [contentView addSubview:lab_orderDate];
        _msg_height = _msg_height + 32;
        //
        UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(0,_msg_height , ScreenWidth, 1)];
        line1.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
        [contentView addSubview:line1];
        _msg_height = _msg_height + 1;
        //客户信息
        UIImageView *image2 = [[UIImageView alloc]initWithFrame:CGRectMake(10, _msg_height, 18, 32)];
        image2.contentMode = UIViewContentModeCenter;
        image2.image = [UIImage imageNamed:@"grab_order_user"];
        [contentView addSubview:image2];
        //名字电话
        NSString *serviceUser= [NSString stringWithFormat:@"%@(%@)",dic[@"userName"],dic[@"userPhone"]];
        size = [serviceUser sizeWithFont:[UIFont systemFontOfSize:13]];
        UILabel *lab_user = [[UILabel alloc]initWithFrame:CGRectMake(28, _msg_height, size.width, 32)];
        lab_user.font = [UIFont systemFontOfSize:13];
        lab_user.text = serviceUser;
        [contentView addSubview:lab_user];
        //类型
        NSString *serviceType= [NSString stringWithFormat:@"%@",dic[@"serviceType"]];
        size = [serviceType sizeWithFont:[UIFont systemFontOfSize:13]];
        UILabel *lab_type = [[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth - 10 - size.width, _msg_height, size.width, 32)];
        lab_type.font = [UIFont systemFontOfSize:13];
        lab_type.text = serviceType;
        [contentView addSubview:lab_type];
        
        UIImageView *image3 = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth - 28 - size.width, _msg_height, 18, 32)];
        image3.contentMode = UIViewContentModeCenter;
        image3.image = [UIImage imageNamed:@"grab_order_type"];
        [contentView addSubview:image3];
        
        _msg_height = _msg_height + 32;
        //提货地址
        UIImageView *image4 = [[UIImageView alloc]initWithFrame:CGRectMake(10, _msg_height, 18, 40)];
        image4.contentMode = UIViewContentModeCenter;
        image4.image = [UIImage imageNamed:@"grab_order_address"];
        [contentView addSubview:image4];
        
        NSString *servicePickup= [NSString stringWithFormat:@"%@",dic[@"pickupAddress"]];
        size = [servicePickup sizeWithFont:[UIFont systemFontOfSize:13]];
        UILabel *lab_pick_up = [[UILabel alloc]initWithFrame:CGRectMake(28, _msg_height, size.width, 40)];
        lab_pick_up.font = [UIFont systemFontOfSize:13];
        lab_pick_up.text = servicePickup;
        lab_pick_up.numberOfLines = 2;
        lab_pick_up.lineBreakMode = NSLineBreakByTruncatingTail;
        CGSize maximumLabelSize = CGSizeMake(100, 9999);//labelsize的最大值
        //关键语句
        CGSize expectSize = [lab_pick_up sizeThatFits:maximumLabelSize];
       // lab_pick_up.frame =CGRectMake(28, _msg_height, size.width, expectSize.height);
        [contentView addSubview:lab_pick_up];
        
        _msg_height = _msg_height + 40;
        //客户地址
        UIImageView *image5 = [[UIImageView alloc]initWithFrame:CGRectMake(10, _msg_height, 18, 40)];
        image5.contentMode = UIViewContentModeCenter;
        image5.image = [UIImage imageNamed:@"grab_order_address"];
        [contentView addSubview:image5];
        
        NSString *serviceUserAddress = [NSString stringWithFormat:@"%@",dic[@"userAddress"]];
        size = [serviceUserAddress sizeWithFont:[UIFont systemFontOfSize:13]];
        UILabel *lab_user_address = [[UILabel alloc]initWithFrame:CGRectMake(28, _msg_height, size.width, 40)];
        lab_user_address.font = [UIFont systemFontOfSize:13];
        lab_user_address.text = serviceUserAddress;
        [contentView addSubview:lab_user_address];

        _msg_height = _msg_height + 40;
        
        UIView *line3 = [[UIView alloc]initWithFrame:CGRectMake(0,_msg_height , ScreenWidth, 5)];
        line3.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
        [contentView addSubview:line3];
        _msg_height = _msg_height + 5;

        
       
    }
    contentView.frame = CGRectMake(contentView.frame.origin.x, contentView.frame.origin.y, contentView.frame.size.width, _msg_height + 20);
     _scrollView.contentSize = CGSizeMake(ScreenWidth, 360 + _msg_height);
}

-(void) getData{
    NSDateFormatter *sf = [[NSDateFormatter alloc]init];
    [sf setDateFormat:@"yyyy-MM-dd"];
    NSString *startDate = [sf stringFromDate:[NSDate date]];
    NSString *endDate = [sf stringFromDate:[NSDate date]];
    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId ,@"page":[NSString stringWithFormat:@"%i",1],@"size":[NSString stringWithFormat:@"%i",20],@"startDate":startDate,@"endDate":endDate,@"query":@"",@"orderType":@"",@"status":@"201,301,401"};
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"order_list_get" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    // [MBProgressHUD showMessage:@"获取订单"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        
        if ([data[@"success"] boolValue]) {

            NSString *content = data[@"result"];
            
            NSLog(@"%@",content);
            _orderData = [NSJSONSerialization JSONObjectWithData:[content dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            
            [self setOrderView:_orderData];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            }];
}

-(void)msg_click:(UIView *)view{
    
    NSDictionary *dic = _msgData[view.tag];
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    NoticeDetailViewController *vc = [sb instantiateViewControllerWithIdentifier:@"notice_detail_view"];
    vc.noticeId = dic[@"id"];
    
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)order_click2:(UIView *)view{
    NSLog(@"order_click2");
    NSDictionary *dic = _orderData[view.tag - 100];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    
    
    OrderDetailViewController *order = [story instantiateViewControllerWithIdentifier:@"order_detail"];
    order.serviceNo = dic[@"serviceNo"];
    [self.navigationController pushViewController:order animated:YES];
}
- (IBAction)search_click:(id)sender {
   
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    
    
    SearchOrderViewController *searchOrderViewController = [story instantiateViewControllerWithIdentifier:@"search_order_view"];
    
    [self.navigationController pushViewController:searchOrderViewController animated:YES];
}

- (IBAction)order_show:(id)sender {
    UIControl *control = sender;
    [UserDefaultUtil saveData:[NSString stringWithFormat:@"%li",(long)control.tag] key:@"main_index"];
    MainUITabBarController *tabBar = self.tabBarController;
    [tabBar showIndex:1];
}

- (IBAction)code_click:(id)sender {
    
    NSLog(@"启动二维码");
    
    static QRCodeReaderViewController *reader = nil;
    static dispatch_once_t onceToken;
    
    
    dispatch_once(&onceToken, ^{
        reader                        = [QRCodeReaderViewController new];
        reader.modalPresentationStyle = UIModalPresentationFormSheet;
    });
    reader.delegate = self;
    
    [reader setCompletionWithBlock:^(NSString *resultAsString) {
        
    }];
    
    [self presentViewController:reader animated:YES completion:NULL];
}
//二维码回调
- (void)reader:(QRCodeReaderViewController *)reader didScanResult:(NSString *)result{
    
    NSLog(@"%@",result);
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    NSError *error;
    NSDictionary * data = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
    if (data != nil) {
         [self getServiceNo:data[@"serviceNo"]];
    }else{
        [MBProgressHUD showError:@"数据格式不正确"];
    }
   
}

- (void)readerDidCancel:(QRCodeReaderViewController *)reader{
    NSLog(@"readerDidCancel被执行了");
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)getServiceNo:(NSString *)serviceNo{
    NSDateFormatter *sf = [[NSDateFormatter alloc]init];
    [sf setDateFormat:@"yyyy-MM-dd"];
    NSString *startDate = @"2016-01-01";
    NSString *endDate = [sf stringFromDate:[NSDate date]];
    
    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId ,@"page":@"1",@"size":[NSString stringWithFormat:@"%i",20],@"startDate":startDate,@"endDate":endDate,@"query":serviceNo,@"orderType":@"",@"status":@"201,401,301,901,501,601,610,701"};
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"order_list_get" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    // [MBProgressHUD showMessage:@"获取订单"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
       
        if ([data[@"success"] boolValue]) {
            NSString *content = data[@"result"];
            
            NSLog(@"%@",content);
            NSArray *array = [NSJSONSerialization JSONObjectWithData:[content dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            if (array.count > 0) {
                
                UIStoryboard *story = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
                
                
                OrderDetailViewController *order = [story instantiateViewControllerWithIdentifier:@"order_detail"];
                order.serviceNo = serviceNo;
                [self.navigationController pushViewController:order animated:YES];
            }else{
                [MBProgressHUD showError:@"无该订单信息"];
            }
        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}

- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return theImage;
}
@end
